from base import errors
from base import controllers as base_ctl
from account.models import AccountModel
from account.models import UserModel
from utils import time_utils


def create_account(master_id, password, typ):
    '''
    创建证
    '''
    obj = AccountModel.objects.filter(master_id=master_id).first()
    data = {
        'master_id': master_id,
        'password': password,
        'typ': typ,
    }
    if obj:
        base_ctl.update_obj(AccountModel, obj.id, data)
    else:
        base_ctl.create_obj(AccountModel, data)


def update_account(obj_id, master_id, password, typ):
    '''
    编辑证
    '''
    obj = base_ctl.get_obj(AccountModel, obj_id)
    data = {
        'master_id': master_id,
        'password': password,
        'typ': typ,
    }
    base_ctl.update_obj(AccountModel, obj_id, data)
    UserModel.objects.filter(master_id=master_id).update(password=password)


def delete_account(obj_id, operator=None):
    '''
    删除证
    '''
    AccountModel.objects.filter(id=obj_id).delete()


def get_accounts(keyword=None, typ=None, page_num=None, page_size=None):
    '''
    获取证列表
    '''
    base_query = AccountModel.objects
    if keyword:
        base_query = base_query.filter(master_id__icontains=keyword)
    if typ:
        base_query = base_query.filter(typ__icontains=typ)
    base_query = base_query.order_by('master_id')
    total = base_query.count()
    objs = base_ctl.query_objs_by_page(base_query, page_num, page_size)
    data_list = []
    for obj in objs:
        data = obj.to_dict()
        data['count'] = UserModel.objects.filter(master_id=obj.master_id).count()
        data_list.append(data)
    data = {
        'total': total,
        'data_list': data_list,
    }
    return data


def get_account(obj_id, operator=None):
    '''
    获取证信息
    '''
    obj = base_ctl.get_obj(AccountModel, obj_id)
    data = obj.to_dict()
    return data